<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" th:replace="~{layout/base :: layout(~{::title}, ~{::content}, ~{::css}, ~{::js})}">
<head>
    <title>标签管理 - 笔记管理系统</title>
    <th:block th:fragment="css">
        <style>
            .tag-container {
                background: white;
                border-radius: 10px;
                padding: 30px;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            }
            .tag-grid {
                display: grid;
                grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
                gap: 20px;
            }
            .tag-item {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                border-radius: 10px;
                padding: 20px;
                transition: all 0.3s;
                position: relative;
                overflow: hidden;
            }
            .tag-item:hover {
                transform: translateY(-5px);
                box-shadow: 0 10px 25px rgba(0,0,0,0.2);
            }
            .tag-item::before {
                content: '';
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(255,255,255,0.1);
                opacity: 0;
                transition: opacity 0.3s;
            }
            .tag-item:hover::before {
                opacity: 1;
            }
            .tag-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 15px;
                position: relative;
                z-index: 1;
            }
            .tag-name {
                font-size: 1.3rem;
                font-weight: 600;
                margin: 0;
            }
            .tag-count {
                background: rgba(255,255,255,0.2);
                padding: 5px 12px;
                border-radius: 15px;
                font-size: 0.875rem;
                backdrop-filter: blur(10px);
            }
            .tag-description {
                margin-bottom: 20px;
                opacity: 0.9;
                line-height: 1.5;
                position: relative;
                z-index: 1;
            }
            .tag-actions {
                display: flex;
                gap: 10px;
                position: relative;
                z-index: 1;
            }
            .tag-actions .btn {
                background: rgba(255,255,255,0.2);
                border: 1px solid rgba(255,255,255,0.3);
                color: white;
                backdrop-filter: blur(10px);
                font-size: 0.875rem;
                padding: 5px 12px;
            }
            .tag-actions .btn:hover {
                background: rgba(255,255,255,0.3);
                border-color: rgba(255,255,255,0.5);
                color: white;
            }
            .empty-state {
                text-align: center;
                padding: 60px 20px;
                color: #666;
            }
            .empty-state i {
                font-size: 4rem;
                color: #ddd;
                margin-bottom: 20px;
            }
            .modal-body .form-group {
                margin-bottom: 20px;
            }
            .hot-tags {
                margin-bottom: 30px;
            }
            .hot-tag-item {
                display: inline-block;
                background: #ff6b6b;
                color: white;
                padding: 8px 15px;
                margin: 5px;
                border-radius: 20px;
                font-size: 0.9rem;
                text-decoration: none;
                transition: all 0.3s;
            }
            .hot-tag-item:hover {
                background: #ff5252;
                color: white;
                transform: scale(1.05);
            }
            .hot-tag-item .count {
                background: rgba(255,255,255,0.3);
                padding: 2px 8px;
                border-radius: 10px;
                margin-left: 8px;
                font-size: 0.8rem;
            }
        </style>
    </th:block>
</head>
<body>
    <div th:fragment="content">
        <!-- 页面标题 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>
                <i class="fas fa-tags me-2"></i>标签管理
            </h2>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#tagModal" onclick="openAddModal()">
                <i class="fas fa-plus me-2"></i>新建标签
            </button>
        </div>

        <!-- 热门标签 -->
        <div class="hot-tags">
            <h5><i class="fas fa-fire me-2 text-danger"></i>热门标签</h5>
            <div id="hotTags">
                <!-- 热门标签将通过AJAX加载 -->
            </div>
        </div>

        <!-- 标签列表 -->
        <div class="tag-container">
            <div id="tagList" class="tag-grid">
                <!-- 标签项将通过AJAX加载 -->
            </div>
        </div>

        <!-- 标签编辑模态框 -->
        <div class="modal fade" id="tagModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="modalTitle">新建标签</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form id="tagForm">
                            <input type="hidden" id="tagId" name="id">
                            <div class="form-group">
                                <label for="tagName" class="form-label">标签名称 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="tagName" name="tagName" required>
                                <div class="form-text">标签名称必须唯一</div>
                            </div>
                            <div class="form-group">
                                <label for="description" class="form-label">描述</label>
                                <textarea class="form-control" id="description" name="description" rows="3" placeholder="请输入标签描述"></textarea>
                            </div>
                            <div class="form-group">
                                <label for="color" class="form-label">颜色</label>
                                <input type="color" class="form-control form-control-color" id="color" name="color" value="#007bff">
                                <div class="form-text">选择标签的显示颜色</div>
                            </div>
                            <div class="form-group">
                                <label for="sortOrder" class="form-label">排序</label>
                                <input type="number" class="form-control" id="sortOrder" name="sortOrder" value="0" min="0">
                                <div class="form-text">数字越小排序越靠前</div>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="saveTag()">保存</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <th:block th:fragment="js">
        <script>
            $(document).ready(function() {
                loadHotTags();
                loadTags();
            });

            // 加载热门标签
            function loadHotTags() {
                $.get('/note/tag/hot', function(data) {
                    if (data.code === 200) {
                        renderHotTags(data.data);
                    }
                });
            }

            // 渲染热门标签
            function renderHotTags(tags) {
                let html = '';
                if (tags.length === 0) {
                    html = '<span class="text-muted">暂无热门标签</span>';
                } else {
                    tags.forEach(function(tag) {
                        html += `
                            <a href="/note?tagId=${tag.id}" class="hot-tag-item">
                                ${tag.tagName}
                                <span class="count">${tag.usageCount || 0}</span>
                            </a>
                        `;
                    });
                }
                $('#hotTags').html(html);
            }

            // 加载标签列表
            function loadTags() {
                $.get('/note/tag/listWithCount', function(data) {
                    if (data.code === 200) {
                        renderTags(data.data);
                    } else {
                        showError('加载标签列表失败：' + data.msg);
                    }
                });
            }

            // 渲染标签列表
            function renderTags(tags) {
                let html = '';
                
                if (tags.length === 0) {
                    html = `
                        <div class="empty-state" style="grid-column: 1 / -1;">
                            <i class="fas fa-tags"></i>
                            <h4>暂无标签</h4>
                            <p>还没有创建任何标签，<a href="#" onclick="openAddModal()" data-bs-toggle="modal" data-bs-target="#tagModal">立即创建</a>第一个标签吧！</p>
                        </div>
                    `;
                } else {
                    tags.forEach(function(tag, index) {
                        // 为每个标签生成不同的渐变色
                        let gradients = [
                            'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                            'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
                            'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
                            'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
                            'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
                            'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)',
                            'linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%)',
                            'linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%)'
                        ];
                        let gradient = gradients[index % gradients.length];
                        
                        html += `
                            <div class="tag-item" style="background: ${gradient};">
                                <div class="tag-header">
                                    <h5 class="tag-name">${tag.tagName}</h5>
                                    <div class="tag-count">${tag.usageCount || 0} 次使用</div>
                                </div>
                                <div class="tag-description">
                                    ${tag.description || '暂无描述'}
                                </div>
                                <div class="tag-actions">
                                    <button class="btn btn-sm" onclick="editTag(${tag.id})" data-bs-toggle="modal" data-bs-target="#tagModal">
                                        <i class="fas fa-edit me-1"></i>编辑
                                    </button>
                                    <a href="/note?tagId=${tag.id}" class="btn btn-sm">
                                        <i class="fas fa-eye me-1"></i>查看笔记
                                    </a>
                                    <button class="btn btn-sm" onclick="deleteTag(${tag.id}, '${tag.tagName}', ${tag.usageCount || 0})">
                                        <i class="fas fa-trash me-1"></i>删除
                                    </button>
                                </div>
                            </div>
                        `;
                    });
                }
                
                $('#tagList').html(html);
            }

            // 打开新建模态框
            function openAddModal() {
                $('#modalTitle').text('新建标签');
                $('#tagForm')[0].reset();
                $('#tagId').val('');
                $('#color').val('#007bff');
            }

            // 编辑标签
            function editTag(id) {
                $('#modalTitle').text('编辑标签');
                
                $.get(`/note/tag/selectById?id=${id}`, function(data) {
                    if (data.code === 200) {
                        let tag = data.data;
                        $('#tagId').val(tag.id);
                        $('#tagName').val(tag.tagName);
                        $('#description').val(tag.description);
                        $('#color').val(tag.color || '#007bff');
                        $('#sortOrder').val(tag.sortOrder || 0);
                    } else {
                        showError('加载标签信息失败：' + data.msg);
                    }
                });
            }

            // 保存标签
            function saveTag() {
                // 验证必填字段
                if (!$('#tagName').val().trim()) {
                    showError('请输入标签名称');
                    return;
                }

                let formData = $('#tagForm').serialize();
                let url = $('#tagId').val() ? '/note/tag/edit' : '/note/tag/add';

                // 检查名称是否重复
                let tagName = $('#tagName').val().trim();
                let tagId = $('#tagId').val();
                
                $.get('/note/tag/checkUnique', {
                    tagName: tagName,
                    id: tagId || ''
                }, function(data) {
                    if (data.code === 200 && data.data === false) {
                        showError('标签名称已存在，请使用其他名称');
                        return;
                    }
                    
                    // 名称唯一，保存标签
                    $.post(url, formData, function(data) {
                        if (data.code === 200) {
                            showSuccess('保存成功');
                            $('#tagModal').modal('hide');
                            loadHotTags();
                            loadTags();
                        } else {
                            showError('保存失败：' + data.msg);
                        }
                    });
                });
            }

            // 删除标签
            function deleteTag(id, name, usageCount) {
                if (usageCount > 0) {
                    if (!confirm(`标签"${name}"已被使用${usageCount}次，删除后相关笔记的标签关联也会被删除。确定要删除吗？`)) {
                        return;
                    }
                } else {
                    if (!confirm(`确定要删除标签"${name}"吗？`)) {
                        return;
                    }
                }
                
                $.post('/note/tag/remove', {ids: id}, function(data) {
                    if (data.code === 200) {
                        showSuccess('删除成功');
                        loadHotTags();
                        loadTags();
                    } else {
                        showError('删除失败：' + data.msg);
                    }
                });
            }

            // 表单提交处理
            $('#tagForm').on('submit', function(e) {
                e.preventDefault();
                saveTag();
            });

            // 模态框关闭时重置表单
            $('#tagModal').on('hidden.bs.modal', function() {
                $('#tagForm')[0].reset();
                $('#tagId').val('');
                $('#color').val('#007bff');
            });

            // 显示成功消息
            function showSuccess(message) {
                alert(message); // 简单实现，可以替换为更好的提示组件
            }

            // 显示错误消息
            function showError(message) {
                alert(message); // 简单实现，可以替换为更好的提示组件
            }
        </script>
    </th:block>
</body>
</html>